import time


def tracker_file_read(tracker_file_url):
    tracker_file = open(tracker_file_url, 'r', encoding='utf-8')
    read = tracker_file.read()
    return read


def conf_file_write(conf_file_url, tracker_list):
    conf_file = open(conf_file_url, 'w+', encoding='utf-8')
    conf_file.writelines(tracker_list)
    print('conf_file:write_success')


def conf_file_read(conf_file_url):
    conf_file = open(conf_file_url, 'r', encoding='utf-8')
    return conf_file.readlines()


def bak_conf_file(conf_file_url):
    read_line = conf_file_read(conf_file_url)
    dict_url = conf_file_url[:conf_file_url.rfind('/')]
    bak_file_name = dict_url + '/bak_aria2_' + str(time.time()) + '.conf'
    bak_file = open(bak_file_name, 'w', encoding='utf-8')
    bak_file.writelines(read_line)
    print('bak_conf_file:success' + bak_file_name)


def update_conf_tracker_list(conf_url, tracker_url):
    bak_conf_file(conf_url)
    conf_file_line = conf_file_read(conf_url)
    track_list = tracker_file_read(tracker_url)
    track = 'bt-tracker=' + track_list
    new_conf_line = []
    conf_len = len(conf_file_line) - 1
    for i in range(conf_len):
        new_conf_line.append(conf_file_line[i])
    new_conf_line.append(track)
    conf_file_write(conf_url, new_conf_line)
